package com.su.dolphin.core.proxy;

import android.graphics.Bitmap;
import android.text.TextUtils;
import android.widget.AbsListView;
import android.widget.ImageView;

import com.lidroid.xutils.BitmapUtils;
import com.lidroid.xutils.bitmap.PauseOnScrollListener;
import com.su.dolphin.DpApp;
import com.su.dolphin.R;
import com.su.dolphin.utils.LogUtil;
import com.su.dolphin.utils.StringUtil;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;

public class ImageLoader {
    private BitmapUtils mBitmapUtils;

    private static class ImageLoaderInstance {
        private static final ImageLoader mImageLoader = new ImageLoader();
    }

    private ImageLoader() {
        mBitmapUtils = new BitmapUtils(DpApp.getContext());
        mBitmapUtils.configDefaultBitmapConfig(Bitmap.Config.RGB_565);
    }

    public static ImageLoader i() {
        return ImageLoaderInstance.mImageLoader;
    }

    /**
     * 设置 listview gridview等, 在滚动的时候不加载图片
     *
     * @param absListView
     */
    public void setOnScrollListener(AbsListView absListView) {
        absListView.setOnScrollListener(new PauseOnScrollListener(mBitmapUtils,
                false, true));
    }

    // 根据根据uri和控件加载 ，一下函数一次类推
    public void loadImage(ImageView imageView, String uri) {
        loadImage(imageView, uri, R.drawable.app_default_bitmap
                , R.drawable.app_default_bitmap);
    }

    public void loadImage(ImageView imageView, String uri, int defaultImage) {
        loadImage(imageView, uri, R.drawable.app_default_bitmap, defaultImage);
    }

    public void loadImage(ImageView imageView, String uri,
                          int defaultLoadingImage, int defaultLoadFailedImage) {
        //LogUtil.i("ImageUrl is " + uri);
        if (imageView.getTag() instanceof String && TextUtils.equals(uri, (String) imageView.getTag()))
            return;
        mBitmapUtils.configDefaultLoadingImage(defaultLoadingImage);
        mBitmapUtils.configDefaultLoadFailedImage(defaultLoadFailedImage);
        mBitmapUtils.display(imageView, StringUtil.urlEncodeURL(uri));
        imageView.setTag(uri);
    }

    /**
     * 清除图片缓存, 让数据重建
     *
     * @param uri
     */
    public void clearCache(String uri) {
        mBitmapUtils.clearCache(uri);
    }
}
